package com.game.server.db;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

public class DBConnectionPool {

    private static final DBConnectionPool instance = new DBConnectionPool();
    private final HikariDataSource writeDataSource;

    private DBConnectionPool() {

        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(DBConfig.url);
        config.setUsername(DBConfig.user);
        config.setPassword(DBConfig.password);
        config.setMaximumPoolSize(DBConfig.MaximumPoolSize);
        config.setMinimumIdle(DBConfig.MaximumPoolSize);
        // config.setMaxLifetime(DBConfig.MaxLifetime);
        // config.setConnectionTimeout(10000);

        writeDataSource = new HikariDataSource(config);

    }

    public static DBConnectionPool getInstance() {
        return instance;
    }


    public Connection getConnection(long timeout) throws SQLException {


       int idleConnections=  writeDataSource.getHikariPoolMXBean().getIdleConnections();
        int a  = writeDataSource.getHikariPoolMXBean().getTotalConnections();
        int aa  = writeDataSource.getHikariPoolMXBean().getActiveConnections();
        System.out.println("当前连接池的总数量: " + a);
        System.out.println("当前连接池的活跃的数量: " + aa);
        System.out.println("当前连接池的空闲数量: " + idleConnections);

        return writeDataSource.getConnection();
    }

    public static void main2(String[] args) {


        HikariConfig config = new HikariConfig();
        config.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/xuanxuanyouquan");
        config.setUsername(DBConfig.user);
        config.setPassword(DBConfig.password);

        HikariDataSource dataSource = new HikariDataSource(config);
        //从数据源获取连接
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        //判断是否成功获取到连接
        if (conn !=null){
            System.out.println("连接成功");
        }else {
            System.out.println("连接失败");
        }
        //释放连接到连接池
        try {
            conn.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        dataSource.close();

        try {
            Connection connection = DBConnectionPool.getInstance().getConnection(100);
            // 使用connection进行数据库操作
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}